
/**
 * Created by ting.zhang on 2020/01/20.
 */
import React from 'react';
import { connect } from 'react-redux';
import {messages} from 'share/common';
import { Form, Button, Spin, Card, Carousel, Icon, Popover} from 'antd';
import travelService from 'containers/request/travel-request/travel.service'
import ZxTicketInfo from 'containers/request/travel-request/travel-slide/zx-ticket-info'

class ZxRecommend extends React.Component{
  selectedTickets = [];
  constructor(props){
    super(props);
    this.state = {
      isLoading: false,
      recommendList: [], //推荐机票列表
      tabIndex: 0, //slider当前页，从0开始
      journeyId: '',
      refundRules: {}, //退改签规则
      maxTicketPrice: ''
    };
  }

  //初始化编辑数据
  componentWillReceiveProps(nextProps) {
    const { failedList, isShowZxRecommend } = this.props.params;
    const isShowZxRecommendNew = nextProps.params.isShowZxRecommend;
    console.log('----componentWillReceiveProps-----')
    if (isShowZxRecommendNew && isShowZxRecommendNew !== isShowZxRecommend) {
      this.setState({recommendList: [], tabIndex: 0, journeyId: ''}, () => {
        setTimeout(() => {
          this.goToPage(0, () => {
            this.getRecommendList();
            // setTimeout(() => {
            //   this.slider.onWindowResized();
            // }, 300)
          });
        }, 300);
      });
    }
  }

  componentWillMount() {
    const { params } = this.props;
  }

  getRecommendList() {
    console.log('----getRecommendList-----')
    const {tabIndex} = this.state;
    const {user, params} = this.props;
    const {failedList} = params;

    this.setState({isLoading: true});
    const {departureDate, departureCityCode, arrivalCityCode, orderBufferType, orderBuffer = 0, ticketPrice = 0, supplierCode,
      economyCabinFullTicketPrice = 0, internationalOrderBufferType, internationalOrderBuffer, isIntFlight} = failedList[tabIndex];
    let ticketPriceNum = Number(ticketPrice);
    const bufferType = isIntFlight ? internationalOrderBufferType : orderBufferType;
    const buffer = isIntFlight ? internationalOrderBuffer : orderBuffer;
    let maxTicketPrice = (bufferType === 1) ?
      Number(ticketPriceNum + Number(economyCabinFullTicketPrice) * buffer / 100).toFixed(2) :
      ((bufferType === 2) ? Number(ticketPriceNum + buffer).toFixed(2) : ticketPriceNum);
    maxTicketPrice = Number(maxTicketPrice);
    travelService.getRecommendList({
      employeeNo: user.employeeID,
      departureDate: departureDate.substr(0, 10), // "2019-12-24"
      departureCityCode,
      arrivalCityCode,
      travelType: 'business',
      maxTicketPrice,
      querySupplierCodeList: supplierCode ? [supplierCode] : []
    }).then(res => {
      this.setState({
        recommendList: res.data.body,
        isLoading: false,
        maxTicketPrice
      });
    }).catch(e => {
      this.setState({isLoading: false});
    });
  }

  // 关闭侧滑
  closeSlide = (result) =>{
    this.props.close(result);
  };

  // 点击轮播图
  goCarouselDetail = (item) => {
    console.log('=====goCarouselDetail====');
  };

  //获取星期几
  getWeed = (value) => {
    switch(value) {
      case 0:
        return messages('request.key33'/*周日*/);
      case 1:
        return messages('request.key34'/*周一*/);
      case 2:
        return messages('request.key35'/*周二*/);
      case 3:
        return messages('request.key36'/*周三*/);
      case 4:
        return messages('request.key37'/*周四*/);
      case 5:
        return messages('request.key38'/*周五*/);
      case 6:
        return messages('request.key39'/*周六*/);
    }
  };

  showTicketChangeRule = (item) => { // 显示退改签政策
    console.log('---showTicketChangeRule-----', item);
    const {priceId, refundChangeRule, subCustomerOrderId} = item;
    let refundRules = {};
    if (subCustomerOrderId) {
      refundRules = JSON.parse(refundChangeRule || '{}');
      this.setState({refundRules});
    } else {
      travelService.queryRefundChangeRuleBefore({priceId}).then(res => {
        if (res && res.status === 200 && res.data && res.data.body) {
          refundRules = res.data.body;
        }
        this.setState({isLoading: false, refundRules});
      }).catch(e => {
        this.setState({isLoading: false});
      });
    }
  };

  onBookOrgTicket = (item) => { // 点击"继续预定原机票"
    console.log('---onBookOrgTicket-----', item);
    item.isRecommend = false;
    this.handleSelectedTickets(item);
  };

  handleBook = (item, subItem) => { // 点击确定推荐机票
    console.log('---handleBook-----', item, subItem);

    const {failedList} = this.props.params;
    const {tabIndex} = this.state;
    const mixedTicketInfo = Object.assign({}, item, subItem);
    mixedTicketInfo.orgOrderInfo = failedList[tabIndex];
    delete mixedTicketInfo.subList;
    mixedTicketInfo.isRecommend = true;
    this.handleSelectedTickets(mixedTicketInfo);
  };

  handleSelectedTickets = (ticketInfo) => {
    console.log('---handleSelectedTickets-----');
    const {failedList, targetFlightForUpd} = this.props.params;
    const {tabIndex} = this.state;
    const index = targetFlightForUpd ? targetFlightForUpd.index : tabIndex;
    this.selectedTickets[index] = ticketInfo;
    const len = failedList.length;
    if(!targetFlightForUpd && tabIndex < len - 1) {
      this.next(tabIndex);
    } else {
      this.closeSlide(this.selectedTickets);
    }
  };

  showSubList = (item) => {
    console.log('---showSubList-----', item);
    const {journeyId, recommendList} = this.state;
    if (item.showExtend) { // 当前item已展开，则点击收起当前item
      item.showExtend = false;
      this.setState({journeyId: ''});
    } else { // 当前item未展开
      if(journeyId) { // 其他item已展开，则收起其他的，展开当前item
        recommendList.map(rec => {
          rec.showExtend = (rec.journeyId === item.journeyId);
        });
      } else { // 没有任何展开的item，则直接展开当前item
        item.showExtend = true;
      }
      this.setState({journeyId: item.journeyId, recommendList});
      this.getSubList(item, item.journeyId);
    }
  };

  //根据某张推荐机票，获取可预定的列表
  getSubList = (item, journeyId) => {
    const {maxTicketPrice} = this.state;
    const {user} = this.props;
    this.setState({isLoading: true});
    travelService.getSubList({
      journeyIdList: [journeyId],
      maxTicketPrice,
      employeeNo: user.employeeID
    }).then(res => {
      if (res && res.status == 200 && res.data && res.data.body) {
        item.subList =  res.data.body;
      }
      this.setState({
        isLoading: false
      });
    }).catch(e => {
      this.setState({isLoading: false});
    });
  };

  next = (tabIndex) => {
    this.slider.slick.slickNext(); // next()
    this.setState({tabIndex: tabIndex + 1}, () => {
      this.getRecommendList();
    });
  };
  prev = () => {
    this.slider.slick.slickPrev(); // prev()
    // this.setState({tabIndex: tabIndex - 1});
  };
  goToPage = (n, callback) => {
    this.slider.slick.slickGoTo(n); // slickGoTo()
    this.setState({tabIndex: n}, () => {
      callback && callback()
    });
  };

  render() {
    const {isLoading, recommendList, tabIndex, journeyId, refundRules} = this.state;
    const {flightNo,preRefundAmount,preChangeAmount,baggage,signTransferRule,refundRuleDetailList,changeRuleDetailList} = refundRules;
    const {info, failedList, targetFlightForUpd} = this.props.params;
    const {item: updateItem, index: updateIndex} = targetFlightForUpd || {};
    let carouselsJSX = [];
    let len = failedList.length;
    let refundRulesContent = (
      <div className="refund-rule-wrapper">
        <div><span className="rule-label">{messages('request.key76'/*航班号*/)}：</span>{flightNo}</div>
        <div><span className="rule-label">{messages('zx.rule.package'/*行李额度*/)}：</span>{baggage}</div>
        <div><span className="rule-label">{messages('zx.rule.sign.transfer'/*签转规则*/)}：</span>{signTransferRule}</div>
        <div><span className="rule-label">{messages('zx.rule.pre.change'/*预估改签费*/)}：</span>{preChangeAmount}</div>
        <div><span className="rule-label">{messages('zx.rule.pre.refund'/*预估退票费*/)}：</span>{preRefundAmount}</div>
        <div>
          <div className="rule-label">{messages('zx.rule.change'/*改签规则*/)}：</div>
          {changeRuleDetailList && changeRuleDetailList.map(obj => (
            <div>{obj.timeScope}：{obj.percent.indexOf('%') < 0 ? obj.percent : messages('zx.rule.percent', {n: obj.percent})}</div>
          ))}
        </div>
        <div>
          <div className="rule-label">{messages('zx.rule.refund'/*退票规则*/)}：</div>
          {refundRuleDetailList && refundRuleDetailList.map(obj => (
            <div>{obj.timeScope}：{obj.percent.indexOf('%') < 0 ? obj.percent : messages('zx.rule.percent', {n: obj.percent})}</div>
          ))}
        </div>
      </div>
    );

    len && failedList.map((item, index) => {
      let {departureDate, subOrderTotalAmount} = item;
      departureDate = departureDate && departureDate.replace ? departureDate.replace(/-/g, '/') : departureDate;
      let dataStr = `${new Date(departureDate).format('yyyy.MM.dd')} ${this.getWeed(new Date(departureDate).getDay())} 
      ${item.departureCityName}-${item.arrivalCityName} `;
      let moneyStr = this.filterMoney(subOrderTotalAmount);

      (!updateItem || updateIndex == index) && carouselsJSX.push(
        <div className="carousel" key={item.carouselOID} onClick={() => this.goCarouselDetail(item)}>
          <div className="title-fail">
            {messages("zx.ticket.fail.title"/*出票失败行程（第{i}程，共{n}个）*/, {i:index+1, n:len})}
          </div>
          <div className="date">{dataStr} ¥{moneyStr}</div>
          <div className="block-area">
            <div className="">
              {dataStr} ¥{moneyStr}
              <span className="refund" onClick={() => this.showTicketChangeRule(item)}>
                <Popover placement="right"
                         trigger="click"
                         title={messages('zx.change.refund.policy', {cm: '退改签政策'})}
                         content={refundRulesContent}
                         overlayStyle={{maxWidth: 500}}>{messages('zx.change.refund.policy', {cm: '退改签政策'})}</Popover>
              </span>
            </div>
            <ZxTicketInfo ticketInfo={item} withTax/>
            <div className="book-org" onClick={() => this.onBookOrgTicket(item)}>
              <span className="book-org-btn">{messages('zx.continue.book.org')/*继续预定原航班*/}</span>
            </div>
          </div>
        </div>
      );
    });

    return (
      <div className="zx-recommend">
        <Spin spinning={isLoading}>
          <div className="overlay"></div>
          <Card className="carousels" key="0">
            <Carousel dots={true} ref={el => (this.slider = el)}>
              {carouselsJSX}
            </Carousel>
          </Card>
          <div className="list-wrapper">
            <div className="header">{messages('zx.flight.tips')/*选择以下推荐航班，可免审批直接出票*/}</div>
            <div className="recommend-list">
              {recommendList.map(item => {
                return (<div className="list-item">
                  <div className="main-item" onClick={() => this.showSubList(item)}>
                    <ZxTicketInfo ticketInfo={item}/>
                    <Icon type="down" className={journeyId && item.showExtend ? "arrow" : "arrow extended"}/>
                  </div>
                  <div className="sub-list">
                    {
                      journeyId && item.showExtend &&  item.subList && item.subList.map(subitem => {
                        return <div className="sub-item">
                          <div className="supplier">{subitem.supplierName}</div>
                          <div className="air-info">
                            {subitem.cabinClassName} {messages('zx.discount', {n:subitem.discount, cm: '{n}折'})}
                            <span className="refund" onClick={() => this.showTicketChangeRule(subitem)}>
                              <Popover placement="right"
                                       trigger="click"
                                       title={messages('zx.change.refund.policy', {cm: '退改签政策'})}
                                       content={refundRulesContent}
                                       overlayStyle={{maxWidth: 500}}>{messages('zx.change.refund.policy', {cm: '退改签政策'})}</Popover>
                            </span>
                          </div>
                          <div className="price-wrapper">
                            <div className="protocol-tag">
                              {subitem.isProtocol && <span className="tag">{messages('zx.price.protocol', {cm: '协议价'})}</span>}
                            </div>
                            <div className="price-fee">{messages('zx.price.fee', {cm: '含服务费价'})} CNY {this.filterMoney(subitem.totalAmount)}</div>
                            <div className="price-tax">CNY <span className="price-tax-amt">{this.filterMoney(subitem.ticketPrice)}</span></div>
                          </div>
                          {subitem.seatNum !== "A" && <div className="remain num">{messages('zx.ticket.remain', {n:subitem.seatNum, cm: '剩余{n}张'})}</div>}
                          {subitem.seatNum === "A" && <div className="remain">{messages('zx.ticket.lot', {cm: '充足'})}</div>}
                          <div className="confirm-book">
                            <Button type="primary" size="small" className="confirm-book-btn" onClick={(e) => this.handleBook(item, subitem)}>
                              {messages('zx.confirm.book', {cm: '预定'})}
                            </Button>
                          </div>
                        </div>
                      })
                    }
                  </div>
                </div>);
              })}
            </div>
          </div>
        </Spin>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
    user: state.login.user
  };
}

const wrappedZxRecommend = Form.create()(ZxRecommend);

export default connect(mapStateToProps)(wrappedZxRecommend);
